package com.fyzk.activity.lottery.zc_new;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.activity.lottery.togetherbuy.HeMaiGenDanActivity;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.lottery.shuzicai.InfoDetailActivity;
import com.fyzk.activity.lottery.zc_new.adapter.ZCBaseAdapter;
import com.fyzk.activity.prize.JLPrizeActivity;
import com.fyzk.activity.prize.JZPrizeActivity;
import com.fyzk.activity.prize.NumberLotteryPrizeHistroyActivity;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.activity.user.NetProgressView;
import com.fyzk.activity.user.touzhu.CommonBetActivity;
import com.fyzk.activity.zhifu.zc.ZhiFu_ZC_Activity;
import com.fyzk.bean.CurrentPhaseInfo;
import com.fyzk.bean.ZCGameQueueItem;
import com.fyzk.betcode.AppLotteryCodeListManager;
import com.fyzk.betcode.CodeBase;
import com.fyzk.betcode.CodeFactory;
import com.fyzk.betcode.ZCBetInfo;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.dialog.SureDialog;
import com.fyzk.interfaces.OnBetCheckedListener;
import com.fyzk.interfaces.ReTryInterface;
import com.fyzk.interfaces.onTopTitleClickListener;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.L;
import com.fyzk.utils.LogUtil;
import com.fyzk.utils.LotteryIDUtils;
import com.fyzk.view.BottomView;
import com.fyzk.view.BottomView.onBottomClickListener;
import com.fyzk.view.DownMenuPopupwindow;
import com.fyzk.view.TopTitleView;
import com.fyzk.view.ViewCallBack;
import com.fyzk.view.ViewCallBack.CountDownInterface;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import http.StringResultBean;

public abstract class ZCBaseActivity_New extends BaseActivity implements
        onTopTitleClickListener, CountDownInterface,
        ReTryInterface, OnBetCheckedListener, onBottomClickListener,
        PhasePopupwindow.PopItemClickListener, DownMenuPopupwindow.DownMenuPopupItemListener {

    private TopTitleView topView;
    private TextView phase_tv;
    private TextView endTime_tv;
    private LinearLayout listTitle_ll;
    private PhasePopupwindow top_popup;
    private ListView listView;
    private NetProgressView mVi_netView;
    private List<ZCGameQueueItem> infors = new ArrayList<ZCGameQueueItem>();
    private BottomView bottomView;
    private TextView bottom_zdy_textView;

    private int popupId = 0;

    protected int changCi = 0;
    protected int zhuShu = 0;

    /**
     * 是否是从支付界面返回
     */
    private boolean isZhiFuBack = false;
    private List<ZCBetInfo> betInfos = new ArrayList<ZCBetInfo>();
    /**
     * 支付列表id
     */
    private int position = -1;
    private String zhiFuBackPhase = "";
    /**
     * 是否可以选择期号
     */
    private boolean isCheckPhase = true;

    private final int maxZhuShu = 10000;

    private List<CurrentPhaseInfo> phaseInfos;

    private DownMenuPopupwindow downMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.zc_new);
        initView();
        ViewCallBack.getInstance().AttachCountDownObj(this);
        isZhiFuBack = getIntent().getBooleanExtra("isZhiFuBack", false);
        position = getIntent().getIntExtra("position", -1);
        isNet();

        downMenu = new DownMenuPopupwindow(this,
                AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT,
                getMenuItems());
        downMenu.setDownMenuPopupOnItemListener(this);

    }

    protected String[] getMenuItems() {
        return new String[]{"开奖公告","玩法介绍","投注查询"};
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (AppLotteryCodeListManager.betType == AppLotteryCodeListManager.FIRSTENTER||AppLotteryCodeListManager.betType == AppLotteryCodeListManager.OKTOBACK) {
            clear();
        } else if (AppLotteryCodeListManager.betType == AppLotteryCodeListManager.MODIFICATIONCODE) {
            changeAdapter(infors);
            onBetChecked();
        }
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        AppLotteryCodeListManager.betType = AppLotteryCodeListManager.FIRSTENTER;
        AppLotteryCodeListManager.chooseId = 0;
        AppLotteryCodeListManager.getInstance().getList().clear();
        super.onDestroy();
    }

    /**
     * 判断是否联网请求（是否是支付返回）	ps:必须初始完控件后执行
     */
    private void isNet() {
        if (isZhiFuBack) {
            betInfos = AppLotteryCodeListManager.getInstance().getZCBetInfoList();
            if (position >= 0) {//修改选号
                ZCBetInfo betInfo = betInfos.get(position);
                for (int i = 0; i < betInfo.infors.size(); i++) {
                    ZCGameQueueItem info1 = betInfo.infors.get(i);
                    ZCGameQueueItem info2 = (ZCGameQueueItem) info1.clone();
                    infors.add(info2);
                }
                zhiFuBackPhase = betInfo.phase;
                phase_tv.setText("第" + zhiFuBackPhase + "期");
                isCheckPhase = false;
                changeAdapter(infors);
                onBetChecked();
            } else {//添加选号
                if (betInfos.size() > 0) {
                    ZCBetInfo betInfo = betInfos.get(0);
                    zhiFuBackPhase = betInfo.phase;
                    phase_tv.setText("第" + zhiFuBackPhase + "期");
                    isCheckPhase = false;
                }
                net();
            }
        } else {
            net();
        }

        if (!isCheckPhase) {
            phase_tv.setCompoundDrawables(null, null, null, null);
        }
    }

    /**
     * 标题
     *
     * @return
     */
    protected abstract String getTopTitle();

    /**
     * 彩种编号
     *
     * @return
     */
    protected abstract int getLotteryID();

    /**
     * 玩法id
     *
     * @return
     */
    protected abstract int getWcodeID(int zhuShu, boolean isDanTuo);

    protected abstract void changeAdapter(List<ZCGameQueueItem> infors);

    protected abstract ZCBaseAdapter getAdapter(List<ZCGameQueueItem> infors);

    protected abstract int minChangCi();

    private void initView() {
        topView = (TopTitleView) findViewById(R.id.zc_toptitle_view);
        topView.setRightImg(R.drawable.downmenu_icon);
        topView.setCenterText(getTopTitle());
        topView.setOnTitleClickListener(this);
        phase_tv = (TextView) findViewById(R.id.zc_phase);
        phase_tv.setOnClickListener(this);
        endTime_tv = (TextView) findViewById(R.id.zc_endtime);
        listTitle_ll = (LinearLayout) findViewById(R.id.zc_listtitle_ll);
        if (isHiddenListHead()) {
            listTitle_ll.setVisibility(View.GONE);
        } else {
            listTitle_ll.setVisibility(View.VISIBLE);
        }
        listView = (ListView) findViewById(R.id.zc_listview);
        listView.setAdapter(getAdapter(infors));
        mVi_netView = (NetProgressView) findViewById(R.id.zc_netprogressview);
        mVi_netView.setRetryInterface(this);
        bottomView = (BottomView) findViewById(R.id.zc_bottom);
        bottomView.setMoRenVisibility(View.VISIBLE);
        bottomView.setMoRenText1("0 注");
        bottomView.setMoRenText2("0 米");
        bottom_zdy_textView = new TextView(this);
        bottom_zdy_textView.setTextColor(getContext().getResources().getColor(R.color.white));
        bottom_zdy_textView.setText("至少选择 " + minChangCi() + " 场");
        bottom_zdy_textView.setGravity(Gravity.CENTER);
        bottomView.addCenterZiDingYiView(bottom_zdy_textView);
        bottomView.setonBottomClickListener(this);
    }

    /**
     * 是否隐藏list的头部view（"赛事/开赛" 等信息）
     * @return
     */
    protected boolean isHiddenListHead() {
        return false;
    }

    private void net() {
        mVi_netView.waiting();
        findCurrentPhase();
    }

    private void findZcRace(String period) {

        JSONObject obj = new JSONObject();
        try {
            obj.put("lotteryType", getLotteryID());
            obj.put("phase", period);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpPostJson(CommandUtil.FINDZCRACE, Commands.FINDZCRACE, obj, false);

    }


    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.FINDCURRENTZCPHASE:
                if (resultBean.getErrorcode().equals("0")) {
                    phaseInfos = JSON.parseArray(resultBean.getData(),
                            CurrentPhaseInfo.class);
                    CurrentPhaseInfo phaseInfo = phaseInfos.get(0);
                    phase_tv.setText("第" + phaseInfo.getPhase() + "期");
                    findZcRace(phaseInfo.getPhase());
                    AppLotteryInfos.setCurrentPrizeInfo(phaseInfo);
                    View view_pop = LayoutInflater.from(this).inflate(
                            R.layout.hm_popupwindow, null);
                    top_popup = new PhasePopupwindow(ZCBaseActivity_New.this, view_pop,
                            AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams
                            .WRAP_CONTENT, phaseInfos);
                    top_popup.setHm_PopupOnItemListener(this);
                } else {
                    showToast(resultBean.getMsg());
                }
                break;
            case CommandUtil.FINDZCRACE:
                if (resultBean.getErrorcode().equals("0")) {
                    infors.clear();
                    infors.addAll(JSON.parseArray(resultBean.getData(), ZCGameQueueItem.class));
                    changeAdapter(infors);
                    mVi_netView.dismiss();
                } else {
                    mVi_netView.fail(resultBean.getMsg());
                }
                break;
        }

    }

    private void findCurrentPhase() {
        try {
            JSONObject params = new JSONObject();
            params.put("lotteryType", getLotteryID());
            httpPostJson(CommandUtil.FINDCURRENTZCPHASE, Commands.FINDCURRENTZCPHASE, params,
                    false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected int getListTitleVis() {
        return View.VISIBLE;
    }

    private void clear() {
        changCi = 0;
        zhuShu = 0;
        for (int i = 0; i < infors.size(); i++) {
            ZCGameQueueItem info = infors.get(i);
            info.clearSelStatu();
        }
        changeAdapter(infors);
        setBtmView();
    }

    public void setBtmView() {
        if (bottomView != null) {
            bottomView.setMoRenText2(changCi + "场");
            bottomView.setMoRenText1(zhuShu + " 注");
            bottomView.setMoRenText2((zhuShu * 2) + " 米");
            String bottomTiShi = "";
            if (changCi == 0) {
                bottomTiShi = "至少选择 " + minChangCi() + " 场";
            } else if (changCi >= minChangCi()) {
                bottomTiShi = "已选 " + changCi + " 场, 可投注 ";
            } else {
                bottomTiShi = "已选 " + changCi + " 场, 还差 " + (minChangCi() - changCi) + " 场";
            }
            bottom_zdy_textView.setText(bottomTiShi);
        }
    }

    @Override
    public void onLeftClick() {
        // TODO Auto-generated method stub
        onBackPressed();
    }

    @Override
    public void onCenterClick() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onRightClick() {
        // TODO Auto-generated method stub
        toHelp();
    }

    @Override
    public void onRight2Click() {
        // TODO Auto-generated method stub

    }

    @Override
    public void countDown() {
        if (null != phaseInfos) {
            for (CurrentPhaseInfo info : phaseInfos) {
                info.setLeftSeconds(info.getLeftSeconds() - 1);
            }
            CurrentPhaseInfo info = phaseInfos.get(popupId);
            endTime_tv.setText(ViewCallBack.getInstance().refreshTimeLeft(info.getLeftSeconds() *
                    1000));
            if (phaseInfos.get(popupId).getLeftSeconds() < 0) {
                showEndTimeDialog(phaseInfos.get(popupId).getPhase());
            }

        }
    }

    SureDialog endTimeDialog;

    /**
     * 时间截止提示对话框
     */
    private void showEndTimeDialog(String period) {
        try {
            if (endTimeDialog == null) {
                endTimeDialog = new SureDialog(this, new SureDialog.OnDialogOKCancleClickListener
                        () {

                    @Override
                    public void onOKClick() {
                        popupId = 0;
                        findCurrentPhase();
                        endTimeDialog.dismiss();
                    }

                    @Override
                    public void onCancleClick() {
                        // TODO Auto-generated method stub
                        endTimeDialog.dismiss();
                    }
                }, "", "第" + period + "期已截止！", "获取新期", "");
            }
            endTimeDialog.show();
        } catch (Exception e) {
            L.e(TAG, e.getMessage());
        }
    }

    @Override
    public void reTry() {
        // TODO Auto-generated method stub
        net();
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
            case R.id.zc_phase:
                if (isCheckPhase) {
                    if (top_popup != null) {
                        top_popup.showPopupWindow(arg0);
                    }
                }
                break;

            default:
                break;
        }
    }

    @Override
    public void onBetChecked() {
        // TODO Auto-generated method stub
        changCi = 0;
        zhuShu = 0;
        jiSuanZhu(infors);
        setBtmView();
    }

    protected abstract void jiSuanZhu(List<ZCGameQueueItem> infors);

    @Override
    public void onBottomLeftClick() {
        // TODO Auto-generated method stub
        clear();
    }

    @Override
    public void onBottomRightClick() {
        // TODO Auto-generated method stub
        if (changCi < minChangCi()) {
            AppToast.getToast().show("请再选 " + (minChangCi() - changCi) + " 场");
            return;
        }
        if (zhuShu > maxZhuShu) {
            AppToast.getToast().show("单笔彩金不得超过" + (maxZhuShu * 2) + "米");
            return;
        }
        touZhu();
    }

    private void touZhu() {
        if (position >= 0) {
            betInfos.remove(position);
        }

        String phase = "";
        try {
            phase = AppLotteryInfos.getPeriod(getLotteryID());
        } catch (Exception e) {
            // TODO: handle exception
        }
        int wcodeID = getWcodeID(zhuShu, false);

        CodeBase codeObj = CodeFactory.getCode(wcodeID);
        String Zhuma = codeObj.betCodeZC(infors);
        String showZhuMa = codeObj.formatHtmlCode2(Zhuma);
        AppLotteryCodeListManager.getInstance().AddZCInfo(wcodeID, Zhuma, showZhuMa, zhuShu,
                phase, infors);
        Intent intent = getZhiFuIntent();
        intent.putExtra(IntentParamUtils.LOTTERYID, getLotteryID());
        startActivity(intent);
        if (!isZhiFuBack) {
        }
//        finish();
    }

    protected Intent getZhiFuIntent() {
        return new Intent(this, ZhiFu_ZC_Activity.class);
    }


    protected abstract void randomBallNum(List<ZCGameQueueItem> infors);


    protected TopTitleView getTopView() {
        return topView;
    }

    /**
     * 进入玩法介绍
     */
    public void toHelp() {
        if (getTopView() != null) {
            downMenu.showPopupWindow(getTopView());
        } else {
            Intent intent = new Intent(getContext(), InfoDetailActivity.class);
            intent.putExtra(IntentParamUtils.TITLE, getHelpTitle());
            intent.putExtra(IntentParamUtils.URL, getHelpUrl());
            startActivity(intent);
        }
    }

    @Override
    public void onMenuItem(int position) {
        LogUtil.d(""+getMenuItems()[position]);
        Intent intent = null;
        switch (position) {
            case 0:

                intent = new Intent();
                switch (getLotteryID()) {
                    case LotteryIDUtils.JLSF_LOTTERY_ID_INT:
                        intent.setClass(getContext(), JLPrizeActivity.class);
                        break;
                    case LotteryIDUtils.JZBF_LOTTERY_ID_INT:
                        intent.setClass(getContext(), JZPrizeActivity.class);
                        break;
                    case LotteryIDUtils.ZCSFC_LOTTERY_ID_INT:
                    case LotteryIDUtils.ZCRXJ_LOTTERY_ID_INT:
                    case LotteryIDUtils.ZCBQC_LOTTERY_ID_INT:
                    case LotteryIDUtils.ZCJQC_LOTTERY_ID_INT:
                        intent.setClass(getContext(), NumberLotteryPrizeHistroyActivity.class);
                        break;
                    case LotteryIDUtils.SSQ_LOTTERY_ID_INT:
                    case LotteryIDUtils.QXC_LOTTERY_ID_INT:
                    case LotteryIDUtils.FC3D_LOTTERY_ID_INT:
                    case LotteryIDUtils.PL3_LOTTERY_ID_INT:
                    case LotteryIDUtils.PL5_LOTTERY_ID_INT:
                    case LotteryIDUtils.DLT_LOTTERY_ID_INT:
                    case LotteryIDUtils.QLC_LOTTERY_ID_INT:
                    case LotteryIDUtils.CQSSC_LOTTERY_ID_INT:
                    case LotteryIDUtils.SD11XUAN5_LOTTERY_ID_INT:
                    case LotteryIDUtils.GD11XUAN5_LOTTERY_ID_INT:
                    case LotteryIDUtils.XJ11XUAN5_LOTTERY_ID_INT:
                    case LotteryIDUtils.ANHUIK3_LOTTERY_ID_INT:
                    case LotteryIDUtils.NXK3_LOTTERY_ID_INT:
                    case LotteryIDUtils.JSK3_LOTTERY_ID_INT:
                    case LotteryIDUtils.JLK3_LOTTERY_ID_INT:
                    case LotteryIDUtils.GXK3_LOTTERY_ID_INT:
                    case LotteryIDUtils.KLSF_LOTTERY_ID_INT:
                    case LotteryIDUtils.GDKLSF_LOTTERY_ID_INT:
                    case LotteryIDUtils.KLPK_LOTTERY_ID_INT:
                        intent.setClass(getContext(), NumberLotteryPrizeHistroyActivity.class);
                        break;
                }
                intent.putExtra(IntentParamUtils.LOTTERYID, getLotteryID());
                break;
            case 1:
                intent = new Intent(getContext(), InfoDetailActivity.class);
                intent.putExtra(IntentParamUtils.TITLE, getHelpTitle());
                intent.putExtra(IntentParamUtils.URL, getHelpUrl());
                break;
            case 2:
                if (MySharedPreferences.getInstance().getLoginStatus()) {
                    intent = new Intent(getContext(), CommonBetActivity.class);
                    intent.putExtra(IntentParamUtils.LOTTERYID, LotteryIDUtils.ZCSFC_LOTTERY_ID_INT);
                } else {
                    AppLotteryInfos.clear();
                    ViewCallBack.getInstance().countDownObjs.clear();
                    ActivityTaskManager.getInstance().closeAllActivity();
                    intent = new Intent(getContext(), LoginActivity.class);
                }
                break;
            default:
                break;
        }
        try {
            startActivity(intent);
        } catch (Exception e) {
            // TODO: handle exception
            LogUtil.v(e.getMessage());
        }
    }

    @Override
    public void menuDismiss() {

    }

    @Override
    public void menuShow() {

    }

    /**
     * 设置玩法介绍的链接
     *
     * @return
     */
    protected abstract String getHelpUrl();

    /**
     * 设置玩法介绍的title
     *
     * @return
     */
    protected abstract String getHelpTitle();


    @Override
    public void onItem(int position) {
        popupId = position;
        CurrentPhaseInfo info = phaseInfos.get(position);
        String phase = info.getPhase();
        phase_tv.setText("第" + phase + "期");
        endTime_tv.setText(ViewCallBack.getInstance().refreshTimeLeft(info.getLeftSeconds() *
                1000));
        findZcRace(phase);
        mVi_netView.waiting();
        clear();
    }

    @Override
    public void popupShow() {

    }

    @Override
    public void popupDismiss() {

    }
}
